package com.limingru.newbee.service.impl;

import com.limingru.newbee.api.vo.GoodsDetailVO;
import com.limingru.newbee.api.vo.GoodsVO;
import com.limingru.newbee.dao.GoodsMapper;
import com.limingru.newbee.entity.Goods;
import com.limingru.newbee.service.GoodsService;
import com.limingru.newbee.util.BeanUtil;
import com.limingru.newbee.util.PageResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Service
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    GoodsMapper goodsMapper;

    @Override
    public PageResult search(Map pageParam) {
        System.out.println(pageParam);
        List<Goods> goods = goodsMapper.searchGoods(pageParam);
        int total = goodsMapper.searchGoodsCount(pageParam);
        PageResult pageResult = new PageResult();
        int pageNumber = Integer.parseInt(pageParam.get("pageNumber").toString());
        int pageSize = Integer.parseInt(pageParam.get("pageSize").toString());
        int totalPages = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
        List<GoodsVO> goodsVOS = BeanUtil.copyList(goods, GoodsVO.class);
        pageResult.setPageNumber(pageNumber);
        pageResult.setPageSize(pageSize);
        pageResult.setTotalCounts(total);
        pageResult.setList(goodsVOS);
        pageResult.setTotalPages(totalPages);
        return pageResult;
    }

    @Override
    public GoodsDetailVO detail(Long goodsId) {
        List<Goods> goods = goodsMapper.selectGoodsByGoodsIds(Arrays.asList(goodsId));
        GoodsDetailVO goodsDetailVO = new GoodsDetailVO();
        if (goods.size() > 0) {
            BeanUtils.copyProperties(goods.get(0), goodsDetailVO);
            return goodsDetailVO;
        }
        return null;
    }
}
